package com.maimang.platform.dsp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.maimang.platform.dsp.constant.AdvertiserApi;
import com.maimang.platform.dsp.entity.*;
import com.maimang.platform.dsp.mapper.OthersMapper;
import com.maimang.platform.dsp.mapper.PromotionMapper;
import com.maimang.platform.dsp.mapper.QualificationMapper;
import com.maimang.platform.dsp.mapper.SubjectMapper;
import com.maimang.platform.dsp.service.AccessTokenService;
import com.maimang.platform.dsp.service.AdvertiserIdsService;
import com.maimang.platform.dsp.service.QualificationService;
import com.maimang.platform.dsp.utils.ApiService;
import com.maimang.platform.lang.ConvertUtils;
import com.maimang.platform.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

/**
 * @author Rocky
 * @version 1.0.0
 * @classname QualificationServiceImpl
 * @description <br>广告主资质主服务层实现类</br>
 * @date 2019-12-17 10:11:36
 * @email jintaozhao@qq.com
 */
@Service
public class QualificationServiceImpl implements QualificationService {

	@Autowired
	private ApiService apiService;

	@Autowired
	private AccessTokenService accessTokenService;

	@Autowired
	private AdvertiserIdsService advertiserIdsService;

	@Autowired
	private QualificationMapper qualificationMapper;

	@Autowired
	private SubjectMapper subjectMapper;

	@Autowired
	private OthersMapper othersMapper;

	@Autowired
	private PromotionMapper promotionMapper;

	/**
	 * 查询广告主资质主信息
	 *
	 * @param advertiserId 广告主资质主ID
	 * @return 广告主资质主信息
	 */
	@Override
	public Qualification selectQualificationById(Long advertiserId) {
		return qualificationMapper.selectQualificationById(advertiserId);
	}

	/**
	 * 同步广告主资质
	 * 包含：
	 *
	 * @param advertiserId 代理商广告主id
	 */
	@Override
	public void syncQualification(Long advertiserId) {
		List<AdvertiserIds> idsList = advertiserIdsService.selectAdvertiserIds(Long.valueOf(advertiserId));

		double total = idsList.size();
		int pageSize = 2000;
		double totalPage = Math.ceil(total / pageSize);
		for (int i = 0; i < totalPage; i++) {
			int beginIndex = i * pageSize;
			int endIndex = (int) Math.min((i + 1) * pageSize, total);

			Executors.newCachedThreadPool().execute(() -> {
				List<AdvertiserIds> advertiserIdsList = idsList.subList(beginIndex, endIndex);

				for (int j = 0; j < advertiserIdsList.size(); j++) {
					AdvertiserIds advertiser = advertiserIdsList.get(j);
					try {
						getQualification(advertiser.getId());
						Thread.sleep(1000);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
	}

	@Override
	public void getQualification(Long id) throws Exception {
		Map param = new HashMap();
		param.put("advertiser_id", id);
		String accessToken = accessTokenService.accessToken();
		JSONObject result = apiService.sendGet(AdvertiserApi.QUALIFICATION, accessToken, param);
		if (result != null) {
			if (result.getInteger("code") == 0) {
				JSONObject data = result.getJSONObject("data");
				if (data.size() == 0) {
					return;
				}
				Qualification qualification = data.toJavaObject(Qualification.class);
				// 先删除旧数据，再插入最新数据
				qualificationMapper.deleteQualificationById(qualification.getAdvertiserId());
				qualificationMapper.insertQualification(qualification);

				Subject subject = qualification.getSubject();
				if (StringUtils.isNotNull(subject)) {
					subject.setAdvertiserId(id);
					subjectMapper.deleteSubjectById(subject.getQualificationId());
					subjectMapper.insertSubject(subject);
				}
				Others[] others = qualification.getOthers();
				if (StringUtils.isNotNull(others) && others.length > 0) {
					for (Others others1 : others) {
						others1.setAdvertiserId(id);
						othersMapper.deleteOthersById(others1.getQualificationId());
						othersMapper.insertOthers(others1);
					}
				}
				Promotion promotion = qualification.getPromotion();
				if (StringUtils.isNotNull(promotion)) {
					promotion.setAdvertiserId(id);
					promotionMapper.deletePromotionById(promotion.getQualificationId());
					promotionMapper.insertPromotion(promotion);
				}
			}
		}
	}

	/**
	 * 查询广告主资质主列表
	 *
	 * @param qualification 广告主资质主信息
	 * @return 广告主资质主集合
	 */
	@Override
	public List<Qualification> selectQualificationList(Qualification qualification) {
		return qualificationMapper.selectQualificationList(qualification);
	}

	/**
	 * 新增广告主资质主
	 *
	 * @param qualification 广告主资质主信息
	 * @return 结果
	 */
	@Override
	public int insertQualification(Qualification qualification) {
		return qualificationMapper.insertQualification(qualification);
	}

	/**
	 * 修改广告主资质主
	 *
	 * @param qualification 广告主资质主信息
	 * @return 结果
	 */
	@Override
	public int updateQualification(Qualification qualification) {
		return qualificationMapper.updateQualification(qualification);
	}

	/**
	 * 删除广告主资质主对象
	 *
	 * @param ids 需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteQualificationByIds(String ids) {
		return qualificationMapper.deleteQualificationByIds(ConvertUtils.toStrArray(ids));
	}

}
